from flask import Flask
from flask_cors import CORS
from datetime import timedelta
from flask_session import Session
import redis
from rel import rel
from flask_profiler import Profiler
import mongoconn
import redisconn as myredis


def create_app(debug=False):
    app = Flask(__name__)

    app.debug = debug

    # 避免浏览器缓存导致下载为上一次的缓存文件
    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0

    # 配置使用flask-profiler来记录api被请求的信息
    app.config["flask_profiler"] = {
        # "enabled": app.config["DEBUG"],
        "enabled": True,
        "storage": {
            "engine": "mongodb",
            # "MONGO_URL": "mongodb://f7689984:f7689984@10.141.7.94:27017/?authSource=flask_profiler",
            "MONGO_URL":mongoconn.MONGO_URL
        },
        "basicAuth":{
            "enabled": True,
            "username": "admin",
            "password": "F7689984"
        },
        "ignore": [
            "^/static/.*"
        ]
    }

    profiler = Profiler()
    # 用flask-profiler初始化app
    profiler.init_app(app)

    # 配置跨域请求
    CORS(app, supports_credentials=True, expose_headers=["Content-Disposition"])

    # 创建一个redis连接，用于存储session信息 rel 指定3号数据库
    redisconn = redis.Redis(host=myredis.HOST, port=myredis.PORT, db=3, password='andy9984')
    # 设置session type
    app.config['SESSION_TYPE'] = 'redis'
    # 设置session连接数据库 此处设置non-decode模式的redis连接，不然会和session值获取有冲突
    app.config['SESSION_REDIS'] = redisconn
    # 设置redis session过期时间
    app.permanent_session_lifetime = timedelta(days=1.0)
    # 设置一个falsk 密钥，用于加密
    app.config['SECRET_KEY'] = '!@#$%^&*()&%$%@#%@#%$#$%^%$&%^&^&*@##%%#^$#$'

    # 初始化Session
    Session(app)

    # 注册项目用到的蓝图组件rel
    app.register_blueprint(rel)

    return app






